package itdep.jsf.internal;

import ga.domain.Entity;
import ga.domain.Pagination;
import ga.domain.PaginationBuilder;
import ga.domain.services.EntityService;
import ga.util.PaginationUtils;
import org.richfaces.model.SortField;
import org.richfaces.model.SortOrder;

import java.io.Serializable;
import java.util.List;

/**
 * @author Ivan Khalopik
 * @version $Revision: 23 $ $Date: 2010-06-19 09:36:09 +0000 (Sat, 19 Jun 2010) $
 */
public class EntityDataProvider<PK extends Serializable, E extends Entity<PK>> implements SortableDataProvider<E> {
	private final EntityService<PK, E> service;

	public EntityDataProvider(EntityService<PK, E> service) {
		this.service = service;
	}

	@Override
	public int getRowCount() {
		return service.getEntitiesCount();
	}

	@Override
	public List<E> getItemsByRange(int firstRow, int endRow) {
		return getItemsByRange(firstRow, endRow, null);
	}

	@Override
	public List<E> getItemsByRange(int firstRow, int endRow, SortOrder sortOrder) {
		return service.getEntities(createPagination(firstRow, endRow, sortOrder));
	}

	@SuppressWarnings({"unchecked"})
	@Override
	public E getItemByKey(Object key) {
		return service.get((PK) key);
	}

	@Override
	public Object getKey(E item) {
		return item.getId();
	}

	private static Pagination createPagination(final int firstRow, final int endRow, final SortOrder sortOrder) {
		final PaginationBuilder builder = PaginationUtils.fromTo(firstRow, endRow);
		if (sortOrder != null) {
			for (SortField field : sortOrder.getFields()) {
				if (field.getName() != null) {
					builder.sort(field.getName(), field.getAscending());
				}
			}
		}
		return builder;
	}
}
